package com.hykj.coca.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.hykj.coca.mapper.BaseMapper;
import com.hykj.coca.config.Config;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by zl on 2015/8/27.
 */

@Service
public abstract class BaseService<D, M extends BaseMapper<D>> implements ChangeModel<D> {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    protected M mapper;

    @Override
    public D change(D model,Map condition) {
        return model;
    }

    public D beforChange(D model,Map condition) {
        if (model == null) {
            return null;
        }
        if (condition == null) {
            return model;
        }
        if(condition.get("s")!=null){
            return model;
        }
        return change(model,condition);
    }


    public PageInfo<D> getList(Map condition, int page) {
        return  this.getList(condition,page,Config.PageSize);
    }


    public PageInfo<D> getList(Map condition, int page,int pageSize) {

        PageHelper.startPage(page, pageSize);
        List<D> models = mapper.getList(condition);
        PageInfo<D> p = new PageInfo<>(models);
        List<D> stream = models.stream().map(model -> {
            return beforChange(model,condition);
        }).collect(Collectors.toList());
        p.setList(stream);
        return p;
    }

    public List<D> getList(Map condition) {
        List<D> list = mapper.getList(condition);
        List<D> stream = list.stream().map(model -> beforChange(model,condition)).collect(Collectors.toList());
        return stream;

    }

    public List<D> getListLite(Map condition) {
        List<D> list = mapper.getList(condition);
        return list;

    }

    public D getById(Integer id) {
        if(id==null){
            return null;
        }
        D model = mapper.getById(id);
        if(model==null){
            return null;
        }
        return beforChange(model,new HashMap());
    }

    public D getById(Integer id,Map condition) {
        if(id==null){
            return null;
        }
        D model = mapper.getById(id);
        if(model==null){
            return null;
        }
        return beforChange(model,condition);
    }

    public Integer getCount(Map condition) {
        return mapper.getCount(condition);
    }

    public boolean update(D model) {

        return mapper.update(model) > 0 ? true : false;
    }

    public boolean create(D model) {

        return mapper.create(model) > 0 ? true : false;
    }

    public Integer delete(Map condition) {
        return mapper.delete(condition);
    }

    public boolean deleteById(Integer id) {
        return mapper.deleteById(id) > 0 ? true : false;
    }
}
